5 * Created on Sep 7, 2006
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
28 * This is a base class for all Query modules.
29 * It provides some common functionality such as constructing various SQL
34 abstract class ApiQueryBase
extends ApiBase
{
36 private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
39 * @param ApiQuery $queryModule
40 * @param string $moduleName
41 * @param string $paramPrefix
43 public function __construct( ApiQuery
$queryModule, $moduleName, $paramPrefix = '' ) {
44 parent
::__construct( $queryModule->getMain(), $moduleName, $paramPrefix );
45 $this->mQueryModule
= $queryModule;
47 $this->resetQueryParams();
50 /************************************************************************//**
51 * @name Methods to implement
56 * Get the cache mode for the data generated by this module. Override
57 * this in the module subclass. For possible return values and other
58 * details about cache modes, see ApiMain::setCacheMode()
60 * Public caching will only be allowed if *all* the modules that supply
61 * data for a given request return a cache mode of public.
63 * @param array $params
66 public function getCacheMode( $params ) {
71 * Override this method to request extra fields from the pageSet
72 * using $pageSet->requestField('fieldName')
73 * @param ApiPageSet $pageSet
75 public function requestExtraData( $pageSet ) {
80 /************************************************************************//**
86 * Get the main Query module
89 public function getQuery() {
90 return $this->mQueryModule
;
94 * @see ApiBase::getParent()
96 public function getParent() {
97 return $this->getQuery();
101 * Get the Query database connection (read-only)
102 * @return DatabaseBase
104 protected function getDB() {
105 if ( is_null( $this->mDb
) ) {
106 $this->mDb
= $this->getQuery()->getDB();
113 * Selects the query database connection with the given name.
114 * See ApiQuery::getNamedDB() for more information
115 * @param string $name Name to assign to the database connection
116 * @param int $db One of the DB_* constants
117 * @param array $groups Query groups
118 * @return DatabaseBase
120 public function selectNamedDB( $name, $db, $groups ) {
121 $this->mDb
= $this->getQuery()->getNamedDB( $name, $db, $groups );
125 * Get the PageSet object to work on
128 protected function getPageSet() {
129 return $this->getQuery()->getPageSet();
134 /************************************************************************//**
140 * Blank the internal arrays with query parameters
142 protected function resetQueryParams() {
143 $this->tables
= array();
144 $this->where
= array();
145 $this->fields
= array();
146 $this->options
= array();
147 $this->join_conds
= array();
151 * Add a set of tables to the internal array
152 * @param string|string[] $tables Table name or array of table names
153 * @param string|null $alias Table alias, or null for no alias. Cannot be
154 * used with multiple tables
156 protected function addTables( $tables, $alias = null ) {
157 if ( is_array( $tables ) ) {
158 if ( !is_null( $alias ) ) {
159 ApiBase
::dieDebug( __METHOD__
, 'Multiple table aliases not supported' );
161 $this->tables
= array_merge( $this->tables
, $tables );
163 if ( !is_null( $alias ) ) {
164 $this->tables
[$alias] = $tables;
166 $this->tables
[] = $tables;
172 * Add a set of JOIN conditions to the internal array
174 * JOIN conditions are formatted as array( tablename => array(jointype,
175 * conditions) e.g. array('page' => array('LEFT JOIN',
176 * 'page_id=rev_page')) . conditions may be a string or an
177 * addWhere()-style array
178 * @param array $join_conds JOIN conditions
180 protected function addJoinConds( $join_conds ) {
181 if ( !is_array( $join_conds ) ) {
182 ApiBase
::dieDebug( __METHOD__
, 'Join conditions have to be arrays' );
184 $this->join_conds
= array_merge( $this->join_conds
, $join_conds );
188 * Add a set of fields to select to the internal array
189 * @param array|string $value Field name or array of field names
191 protected function addFields( $value ) {
192 if ( is_array( $value ) ) {
193 $this->fields
= array_merge( $this->fields
, $value );
195 $this->fields
[] = $value;
200 * Same as addFields(), but add the fields only if a condition is met
201 * @param array|string $value See addFields()
202 * @param bool $condition If false, do nothing
203 * @return bool $condition
205 protected function addFieldsIf( $value, $condition ) {
207 $this->addFields( $value );
216 * Add a set of WHERE clauses to the internal array.
217 * Clauses can be formatted as 'foo=bar' or array('foo' => 'bar'),
218 * the latter only works if the value is a constant (i.e. not another field)
220 * If $value is an empty array, this function does nothing.
222 * For example, array('foo=bar', 'baz' => 3, 'bla' => 'foo') translates
223 * to "foo=bar AND baz='3' AND bla='foo'"
224 * @param string|array $value
226 protected function addWhere( $value ) {
227 if ( is_array( $value ) ) {
228 // Sanity check: don't insert empty arrays,
229 // Database::makeList() chokes on them
230 if ( count( $value ) ) {
231 $this->where
= array_merge( $this->where
, $value );
234 $this->where
[] = $value;
239 * Same as addWhere(), but add the WHERE clauses only if a condition is met
240 * @param string|array $value
241 * @param bool $condition If false, do nothing
242 * @return bool $condition
244 protected function addWhereIf( $value, $condition ) {
246 $this->addWhere( $value );
255 * Equivalent to addWhere(array($field => $value))
256 * @param string $field Field name
257 * @param string $value Value; ignored if null or empty array;
259 protected function addWhereFld( $field, $value ) {
260 // Use count() to its full documented capabilities to simultaneously
261 // test for null, empty array or empty countable object
262 if ( count( $value ) ) {
263 $this->where
[$field] = $value;
268 * Add a WHERE clause corresponding to a range, and an ORDER BY
269 * clause to sort in the right direction
270 * @param string $field Field name
271 * @param string $dir If 'newer', sort in ascending order, otherwise
272 * sort in descending order
273 * @param string $start Value to start the list at. If $dir == 'newer'
274 * this is the lower boundary, otherwise it's the upper boundary
275 * @param string $end Value to end the list at. If $dir == 'newer' this
276 * is the upper boundary, otherwise it's the lower boundary
277 * @param bool $sort If false, don't add an ORDER BY clause
279 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
280 $isDirNewer = ( $dir === 'newer' );
281 $after = ( $isDirNewer ?
'>=' : '<=' );
282 $before = ( $isDirNewer ?
'<=' : '>=' );
283 $db = $this->getDB();
285 if ( !is_null( $start ) ) {
286 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
289 if ( !is_null( $end ) ) {
290 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
294 $order = $field . ( $isDirNewer ?
'' : ' DESC' );
296 $optionOrderBy = isset( $this->options
['ORDER BY'] )
297 ?
(array)$this->options
['ORDER BY']
299 $optionOrderBy[] = $order;
300 $this->addOption( 'ORDER BY', $optionOrderBy );
305 * Add a WHERE clause corresponding to a range, similar to addWhereRange,
306 * but converts $start and $end to database timestamps.
308 * @param string $field
310 * @param string $start
314 protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
315 $db = $this->getDb();
316 $this->addWhereRange( $field, $dir,
317 $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
321 * Add an option such as LIMIT or USE INDEX. If an option was set
322 * before, the old value will be overwritten
323 * @param string $name Option name
324 * @param string $value Option value
326 protected function addOption( $name, $value = null ) {
327 if ( is_null( $value ) ) {
328 $this->options
[] = $name;
330 $this->options
[$name] = $value;
335 * Execute a SELECT query based on the values in the internal arrays
336 * @param string $method Function the query should be attributed to.
337 * You should usually use __METHOD__ here
338 * @param array $extraQuery Query data to add but not store in the object
344 * 'join_conds' => ...
346 * @return ResultWrapper
348 protected function select( $method, $extraQuery = array() ) {
350 $tables = array_merge(
352 isset( $extraQuery['tables'] ) ?
(array)$extraQuery['tables'] : array()
354 $fields = array_merge(
356 isset( $extraQuery['fields'] ) ?
(array)$extraQuery['fields'] : array()
358 $where = array_merge(
360 isset( $extraQuery['where'] ) ?
(array)$extraQuery['where'] : array()
362 $options = array_merge(
364 isset( $extraQuery['options'] ) ?
(array)$extraQuery['options'] : array()
366 $join_conds = array_merge(
368 isset( $extraQuery['join_conds'] ) ?
(array)$extraQuery['join_conds'] : array()
371 // getDB has its own profileDBIn/Out calls
372 $db = $this->getDB();
374 $this->profileDBIn();
375 $res = $db->select( $tables, $fields, $where, $method, $options, $join_conds );
376 $this->profileDBOut();
382 * @param string $query
383 * @param string $protocol
384 * @return null|string
386 public function prepareUrlQuerySearchString( $query = null, $protocol = null ) {
387 $db = $this->getDb();
388 if ( !is_null( $query ) ||
$query != '' ) {
389 if ( is_null( $protocol ) ) {
390 $protocol = 'http://';
393 $likeQuery = LinkFilter
::makeLikeArray( $query, $protocol );
395 $this->dieUsage( 'Invalid query', 'bad_query' );
398 $likeQuery = LinkFilter
::keepOneWildcard( $likeQuery );
400 return 'el_index ' . $db->buildLike( $likeQuery );
401 } elseif ( !is_null( $protocol ) ) {
402 return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() );
409 * Filters hidden users (where the user doesn't have the right to view them)
410 * Also adds relevant block information
412 * @param bool $showBlockInfo
415 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
416 $this->addTables( 'ipblocks' );
417 $this->addJoinConds( array(
418 'ipblocks' => array( 'LEFT JOIN', 'ipb_user=user_id' ),
421 $this->addFields( 'ipb_deleted' );
423 if ( $showBlockInfo ) {
424 $this->addFields( array( 'ipb_id', 'ipb_by', 'ipb_by_text', 'ipb_reason', 'ipb_expiry', 'ipb_timestamp' ) );
427 // Don't show hidden names
428 if ( !$this->getUser()->isAllowed( 'hideuser' ) ) {
429 $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' );
435 /************************************************************************//**
436 * @name Utility methods
441 * Add information (title and namespace) about a Title object to a
443 * @param array $arr Result array à la ApiResult
444 * @param Title $title
445 * @param string $prefix Module prefix
447 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
448 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
449 $arr[$prefix . 'title'] = $title->getPrefixedText();
453 * Add a sub-element under the page element with the given page ID
454 * @param int $pageId Page ID
455 * @param array $data Data array à la ApiResult
456 * @return bool Whether the element fit in the result
458 protected function addPageSubItems( $pageId, $data ) {
459 $result = $this->getResult();
460 $result->setIndexedTagName( $data, $this->getModulePrefix() );
462 return $result->addValue( array( 'query', 'pages', intval( $pageId ) ),
463 $this->getModuleName(),
468 * Same as addPageSubItems(), but one element of $data at a time
469 * @param int $pageId Page ID
470 * @param array $item Data array à la ApiResult
471 * @param string $elemname XML element name. If null, getModuleName()
473 * @return bool Whether the element fit in the result
475 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
476 if ( is_null( $elemname ) ) {
477 $elemname = $this->getModulePrefix();
479 $result = $this->getResult();
480 $fit = $result->addValue( array( 'query', 'pages', $pageId,
481 $this->getModuleName() ), null, $item );
485 $result->setIndexedTagName_internal( array( 'query', 'pages', $pageId,
486 $this->getModuleName() ), $elemname );
492 * Set a query-continue value
493 * @param string $paramName Parameter name
494 * @param string|array $paramValue Parameter value
496 protected function setContinueEnumParameter( $paramName, $paramValue ) {
497 $this->getResult()->setContinueParam( $this, $paramName, $paramValue );
501 * Convert an input title or title prefix into a dbkey.
503 * $namespace should always be specified in order to handle per-namespace
504 * capitalization settings.
506 * @param string $titlePart Title part
507 * @param int $defaultNamespace Namespace of the title
508 * @return string DBkey (no namespace prefix)
510 public function titlePartToKey( $titlePart, $namespace = NS_MAIN
) {
511 $t = Title
::makeTitleSafe( $namespace, $titlePart . 'x' );
513 $this->dieUsageMsg( array( 'invalidtitle', $titlePart ) );
515 if ( $namespace != $t->getNamespace() ||
$t->isExternal() ) {
516 // This can happen in two cases. First, if you call titlePartToKey with a title part
517 // that looks like a namespace, but with $defaultNamespace = NS_MAIN. It would be very
518 // difficult to handle such a case. Such cases cannot exist and are therefore treated
519 // as invalid user input. The second case is when somebody specifies a title interwiki
521 $this->dieUsageMsg( array( 'invalidtitle', $titlePart ) );
524 return substr( $t->getDbKey(), 0, -1 );
528 * Gets the personalised direction parameter description
530 * @param string $p ModulePrefix
531 * @param string $extraDirText Any extra text to be appended on the description
534 public function getDirectionDescription( $p = '', $extraDirText = '' ) {
536 "In which direction to enumerate{$extraDirText}",
537 " newer - List oldest first. Note: {$p}start has to be before {$p}end.",
538 " older - List newest first (default). Note: {$p}start has to be later than {$p}end.",
543 * @param string $hash
546 public function validateSha1Hash( $hash ) {
547 return preg_match( '/^[a-f0-9]{40}$/', $hash );
551 * @param string $hash
554 public function validateSha1Base36Hash( $hash ) {
555 return preg_match( '/^[a-z0-9]{31}$/', $hash );
559 * Check whether the current user has permission to view revision-deleted
563 public function userCanSeeRevDel() {
564 return $this->getUser()->isAllowedAny(
574 /************************************************************************//**
580 * Estimate the row count for the SELECT query that would be run if we
581 * called select() right now, and check if it's acceptable.
582 * @deprecated since 1.24
583 * @return bool True if acceptable, false otherwise
585 protected function checkRowCount() {
586 wfDeprecated( __METHOD__
, '1.24' );
587 $db = $this->getDB();
588 $this->profileDBIn();
589 $rowcount = $db->estimateRowCount(
596 $this->profileDBOut();
598 if ( $rowcount > $this->getConfig()->get( 'APIMaxDBRows' ) ) {
606 * Convert a title to a DB key
607 * @deprecated since 1.24, past uses of this were always incorrect and should
608 * have used self::titlePartToKey() instead
609 * @param string $title Page title with spaces
610 * @return string Page title with underscores
612 public function titleToKey( $title ) {
613 wfDeprecated( __METHOD__
, '1.24' );
614 // Don't throw an error if we got an empty string
615 if ( trim( $title ) == '' ) {
618 $t = Title
::newFromText( $title );
620 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
623 return $t->getPrefixedDBkey();
627 * The inverse of titleToKey()
628 * @deprecated since 1.24, unused and probably never needed
629 * @param string $key Page title with underscores
630 * @return string Page title with spaces
632 public function keyToTitle( $key ) {
633 wfDeprecated( __METHOD__
, '1.24' );
634 // Don't throw an error if we got an empty string
635 if ( trim( $key ) == '' ) {
638 $t = Title
::newFromDBkey( $key );
639 // This really shouldn't happen but we gotta check anyway
641 $this->dieUsageMsg( array( 'invalidtitle', $key ) );
644 return $t->getPrefixedText();
648 * Inverse of titlePartToKey()
649 * @deprecated since 1.24, unused and probably never needed
650 * @param string $keyPart DBkey, with prefix
651 * @return string Key part with underscores
653 public function keyPartToTitle( $keyPart ) {
654 wfDeprecated( __METHOD__
, '1.24' );
655 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, -1 );
664 abstract class ApiQueryGeneratorBase
extends ApiQueryBase
{
666 private $mGeneratorPageSet = null;
669 * Switch this module to generator mode. By default, generator mode is
670 * switched off and the module acts like a normal query module.
671 * @since 1.21 requires pageset parameter
672 * @param ApiPageSet $generatorPageSet ApiPageSet object that the module will get
673 * by calling getPageSet() when in generator mode.
675 public function setGeneratorMode( ApiPageSet
$generatorPageSet ) {
676 if ( $generatorPageSet === null ) {
677 ApiBase
::dieDebug( __METHOD__
, 'Required parameter missing - $generatorPageSet' );
679 $this->mGeneratorPageSet
= $generatorPageSet;
683 * Get the PageSet object to work on.
684 * If this module is generator, the pageSet object is different from other module's
687 protected function getPageSet() {
688 if ( $this->mGeneratorPageSet
!== null ) {
689 return $this->mGeneratorPageSet
;
692 return parent
::getPageSet();
696 * Overrides ApiBase to prepend 'g' to every generator parameter
697 * @param string $paramName Parameter name
698 * @return string Prefixed parameter name
700 public function encodeParamName( $paramName ) {
701 if ( $this->mGeneratorPageSet
!== null ) {
702 return 'g' . parent
::encodeParamName( $paramName );
704 return parent
::encodeParamName( $paramName );
709 * Overridden to set the generator param if in generator mode
710 * @param string $paramName Parameter name
711 * @param string|array $paramValue Parameter value
713 protected function setContinueEnumParameter( $paramName, $paramValue ) {
714 if ( $this->mGeneratorPageSet
!== null ) {
715 $this->getResult()->setGeneratorContinueParam( $this, $paramName, $paramValue );
717 parent
::setContinueEnumParameter( $paramName, $paramValue );
722 * @see ApiBase::getHelpFlags()
724 * Corresponding messages: api-help-flag-generator
726 protected function getHelpFlags() {
727 $flags = parent
::getHelpFlags();
728 $flags[] = 'generator';
733 * Execute this module as a generator
734 * @param ApiPageSet $resultPageSet All output should be appended to this object
736 abstract public function executeGenerator( $resultPageSet );